/*
 * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * This file is part of Harmattan SmashMiner OpenGL game application.
 * 
 * Harmattan SmashMiner OpenGL Example Application version 1.0.0
 *  
 * Latest update: 15.4.2011
 *
 * The Harmattan SmashMiner OpenGL example application demonstrates how to use 
 * the OpenGL ES in Harmattan devices.
 *
 * This example is provided as a starting point for 3rd party
 * developers (you) to ease the implementation of OpenGL based 
 * games. Ideas, parts of code or methodologies that this
 * example application uses can be freely used without restrictions.
 *
 * See file README.txt how to build and compile this example application
 * in the Harmattan SDK environment. 
 * 
 * See file INSTALL.txt to find out what is required to run this
 * application and how to install the application to the device or
 * alternatively in QEMU-emulator.
 *
 * The LICENSE.txt file explains the license this software is provided
 * with. A copy of the same license is included in this source file.
 * 
 */

/*
 * Copyright (C) 2011 by Nokia Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*!
  \class GameSettings

Persistent user preferences are stored to the game settings. Settings contain values for music and sound effects level, difficulty, left handed mode, rewind mode and high scores. Class \c GameSettings is a container for these runtime user settings and it also loads settings from file when constructed and saves settings to file a when \c save() method is called.  Settings can be reseted to it's default values by calling \c resetToDefaults(). Class \c GameSettings also provides \c HighScoreModel for the \c HighScores.qml view.

Class \c GameSettings contains member \c settings which is instance of \c QSettings. \c QSettings is used to handle storing of the settings permanently and platform independently. On the \c Unix environments the actual game settings are stored under \c ~/.config/Nokia/ to a file \c SmashMiner.conf. If \c SmashMiner.conf does not exist the default setting values are used.


\section addingGameSettings Adding New Game Settings

Here are the instructions how to add new game settings item and how it can be exposed to QML side. All settings values need to have signal to notify the value change, getter and setter and name and default value definitions.

Firs you must add a variable for your setting value. \c GameSettings contains each setting value as a member variable. Private member variable \c bool \c lefthanded is added to a \c gamesettings.h:
\code
private:
...
    /// Left handed mode, default false
    bool lefthanded;
...
\endcode

Next some defines are needed. Settings value \c bool \c lefthanded has following defines at the \c gamesettings.h:
\code
...
#define GS_LEFT_HANDED "left_handed"
#define GS_LEFT_HANDED_DEFAULT false
...
\endcode
The first define \c GS_LEFT_HANDED is the name of the setting to be used with \c QSettings. And second define \c GS_LEFT_HANDED_DEFAULT is the default value.

Then at the constructor of the GameSettings the lefthanded value is loaded from the settings file by the name \c GS_LEFT_HANDED. If value does not exist the \c GS_LEFT_HANDED_DEFAULT is used:
\code
...
lefthanded = settings->value(GS_LEFT_HANDED, GS_LEFT_HANDED_DEFAULT).toBool();
...
\endcode

Next we declare setter and getter for \c lefthanded to \c gamesettings.h as follows:
\code
...
inline bool leftHanded() { return lefthanded; }
...
void setLeftHanded(bool);
...
\endcode
The getter \c leftHanded() is implemented to the header as a \c inline function.

Then we implement the \c lefthanded setter is to the \c gamesettings.cpp.
\code
...
void GameSettings::setLeftHanded(bool lefthanded)
{
    if (this->lefthanded != lefthanded) {
        this->lefthanded = lefthanded;
        emit leftHandedChanged(lefthanded);
    }
}
...
\endcode
At the setter the new value is set and signal at the change is emitted only when the value changes. This prevents the unnecessary signal emittions.

Next we must declare the \c leftHandedChanged(bool) signal to the \c gamesettings.h:
\code
...
signals:
...
    void leftHandedChanged(bool);
...
\endcode

Then this signal is connected to the slot at the constructor of the \c GameWidget:
\code
...
connect(settings, SIGNAL(leftHandedChanged(bool)), this, SLOT(setLeftHandedness(bool)));
...
\endcode

Class \c GameAppViewer has member \c GameSettings \c *settings;. Reference to \c GameSettings is given to \c GameWidget when constructed.
Signal is emitted for \c GameWidget to slot \c setLeftHandedness(bool) when \c lefthanded value changes.


\subsection exposingSettingsToQML Exposing settings to QML

Settings are used also from QML views. \c GameSettings instance is exposed to QML via context property \c gameSettings set at the \c main.cpp:
\code
...
context->setContextProperty("gameSettings", viewer.getSettings());
...
\endcode

Some changes are required to \c gamesettings.h to expose properties and methods to QML.
For example \c lefthanded setting value is exposed to QML as property:
\code
...
Q_PROPERTY(bool leftHanded READ leftHanded WRITE setLeftHanded NOTIFY leftHandedChanged)
...
\endcode

At the QML side the property can be used like any QML property:
\code
...
Switch {
        id: leftHandedSwitch

        width: buttonWidth
        height: buttonHeight
        onOnChanged: gameSettings.leftHanded = leftHandedSwitch.on
        Component.onCompleted: {
                if (gameSettings.leftHanded) {
                        leftHandedSwitch.state = "on";
                }
                else {
                        leftHandedSwitch.state = "off";
                }
        }
}
...
\endcode

If the property is changed from the QML side then the \c NOTIFY signal is emitted. Signal is connected at the C++ code to a slot and notification at the changed setting is received to the slot on C++ side.

For the \c HighScores.qml view some public methods are exposed as invokables:
\code
...
Q_INVOKABLE int setHighScore(QString, int, QString);
Q_INVOKABLE bool isHighScore(int);
Q_INVOKABLE HighScoreModel* getHighScoreModel();
...
\endcode

For saving settings and resetting values from QML and two methods needs to be exposed:
\code
...
Q_INVOKABLE void save();
Q_INVOKABLE void resetToDefaults();
...
\endcode

Method \c save() is called on \c onBackClicked slot when returning from settings QML view by pressing back button:
\code
...
    ViewFooter {
        id: settingsFooter

        width: parent.width
        height: headerHeight

        onBackClicked: {
            gameSettings.save();
            soundEngine.playMenuSound();
            back();
        }
...
\endcode
*/

#include "gamesettings.h"

#include "highscoremodel.h"

#include <QSettings>
#include <QDebug>

/*!
    Constructs GameSettings. Initializes also QSettings and loads game settings from file.
*/
GameSettings::GameSettings(QObject *parent) 
    : QObject(parent)
    , settings(new QSettings(QSettings::UserScope, "Nokia", "SmashMiner", this))
#ifdef SMASHMINER_CONFIG_ENABLE_ROTATION_SENSOR
    , rotationsensitivity_x(0.0)
    , rotationsensitivity_y(0.0)
#endif  // SMASHMINER_CONFIG_ENABLE_ROTATION_SENSOR
#ifdef SMASHMINER_CONFIG_ENABLE_ACCELERATION_SENSOR
    , accelerationsensitivity_z(0)
#endif
    , highScoreModel(new HighScoreModel(this))
{
    difficulty = settings->value(GS_DIFFICULTY, GS_DIFFICULTY_DEFAULT).toInt();
    sensitivity = settings->value(GS_SENSITIVITY, GS_SENSITIVITY_DEFAULT).toInt();
    musiclevel = settings->value(GS_MUSIC_LEVEL, GS_MUSIC_LEVEL_DEFAULT).toInt();
    soundlevel = settings->value(GS_SOUND_LEVEL, GS_SOUND_LEVEL_DEFAULT).toInt();
    lefthanded = settings->value(GS_LEFT_HANDED, GS_LEFT_HANDED_DEFAULT).toBool();
    rewind = settings->value(GS_REWIND, GS_REWIND_DEFAULT).toBool();

#ifdef SMASHMINER_CONFIG_ENABLE_ROTATION_SENSOR
    settings->beginGroup(GS_GROUP_ROTATION);
    rotationsensitivity_x = settings->value(GS_ROTATION_SENSITIVITY_X,
                                           GS_ROTATION_SENSITIVITY_X_DEFAULT).toFloat();
    rotationsensitivity_y = settings->value(GS_ROTATION_SENSITIVITY_Y,
                                           GS_ROTATION_SENSITIVITY_Y_DEFAULT).toFloat();
    settings->endGroup();
#endif
#ifdef SMASHMINER_CONFIG_ENABLE_ACCELERATION_SENSOR
    settings->beginGroup(GS_GROUP_ACCELERATION);
    accelerationsensitivity_z = settings->value(GS_ACCELERATION_SENSITIVITY_Z,
                                           GS_ACCELERATION_SENSITIVITY_Z_DEFAULT).toInt();
    settings->endGroup();
#endif

    readHighScore();
}

/*!
  Saves settings to a SmashMiner.conf file.
*/
void GameSettings::save() 
{
    settings->setValue(GS_DIFFICULTY, difficulty);
    settings->setValue(GS_SENSITIVITY, sensitivity);
    settings->setValue(GS_MUSIC_LEVEL, musiclevel);
    settings->setValue(GS_SOUND_LEVEL, soundlevel);
    settings->setValue(GS_LEFT_HANDED, lefthanded);
    settings->setValue(GS_REWIND, rewind);
#ifdef SMASHMINER_CONFIG_ENABLE_ROTATION_SENSOR
    settings->beginGroup(GS_GROUP_ROTATION);
    settings->setValue(GS_ROTATION_SENSITIVITY_X, QString().setNum(rotationsensitivity_x));
    settings->setValue(GS_ROTATION_SENSITIVITY_Y, QString().setNum(rotationsensitivity_y));
    settings->endGroup();
#endif
#ifdef SMASHMINER_CONFIG_ENABLE_ACCELERATION_SENSOR
    settings->beginGroup(GS_GROUP_ACCELERATION);
    settings->setValue(GS_ACCELERATION_SENSITIVITY_Z, accelerationsensitivity_z);
    settings->endGroup();
#endif
}

/*!
  Resets settings to a default values.
*/
void GameSettings::resetToDefaults() 
{
    settings->clear();
}

/*!
  Setter for difficulty.
*/
void GameSettings::setDifficultyLevel(int difficulty) 
{
    if (this->difficulty != difficulty) {
        this->difficulty = difficulty;
        emit difficultyChanged();
    }
}

/*!
  Setter for steering sensitivity.
*/
void GameSettings::setSteeringSensitivity(int sensitivity) 
{
    this->sensitivity = sensitivity;
}

/*!
  Setter for music level.
*/
void GameSettings::setMusicLevel(int musiclevel) 
{
    if (this->musiclevel != musiclevel) {
        this->musiclevel = musiclevel;
        emit musicLevelChanged(musiclevel);
    }
}

/*!
  Setter for sound level.
*/
void GameSettings::setSoundLevel(int soundlevel) 
{
    if (this->soundlevel != soundlevel) {
        this->soundlevel = soundlevel;
        emit soundLevelChanged(soundlevel);
    }
}

/*!
  Setter for left handedness.
*/
void GameSettings::setLeftHanded(bool lefthanded) 
{
    if (this->lefthanded != lefthanded) {
        this->lefthanded = lefthanded;
        emit leftHandedChanged(lefthanded);
    }
}

/*!
  Setter for rewind mode.
*/
void GameSettings::setEndRewind(bool rewind) 
{
    if (this->rewind != rewind) {
        this->rewind = rewind;
        emit endRewindChanged(rewind);
    }
}

#ifdef SMASHMINER_CONFIG_ENABLE_ROTATION_SENSOR
void GameSettings::setRotationSensitivityX(FPtype value) 
{
    rotationsensitivity_x = value;
}

void GameSettings::setRotationSensitivityY(FPtype value) 
{
    rotationsensitivity_y = value;
}
#endif  // SMASHMINER_CONFIG_ENABLE_ROTATION_SENSOR

#ifdef SMASHMINER_CONFIG_ENABLE_ACCELERATION_SENSOR
void GameSettings::setAccelerationSensitivityZ(int value) 
{
    accelerationsensitivity_z = value;
}
#endif  // SMASHMINER_CONFIG_ENABLE_ACCELERATION_SENSOR

/*!
  Checks if \a score is new high score.
*/
bool GameSettings::isHighScore(int score)
{
    int size = settings->beginReadArray(GS_GROUP_HIGHSCORES);

    if (size < 5) {
        settings->endArray();
        return true;
    }

     for (int i = 0; i < size; ++i) {
         settings->setArrayIndex(i);
         if (score >= settings->value("score").toInt()) {
             settings->endArray();
             return true;
         }
     }

     settings->endArray();

    return false;
}

/*!
  Sets new high score to its correct place to a high score list.
  Removes the last score from list if list gets too long.
*/
int GameSettings::setHighScore(QString name, int score, QString time)
{
    bool insert=false;

    int newHighScoreIndex = -1;

    if (highScoreList.size() == 0)
    {
        HighScore newScore;
        newScore.name = name;
        newScore.score = score;
        newScore.time = time;
        newScore.date = QDate::currentDate();
        highScoreList.insert(0,newScore);
        newHighScoreIndex = 0;
    } else {
        for (int i = 0; i < highScoreList.size(); ++i) {
            if (score >= highScoreList.at(i).score && !insert) {
                HighScore newScore;
                newScore.name = name;
                newScore.score = score;
                newScore.time = time;
                newScore.date = QDate::currentDate();
                highScoreList.insert(i,newScore);
                newHighScoreIndex = i;
                insert = true;
            }
        }

        if (!insert) {
            HighScore newScore;
            newScore.name = name;
            newScore.score = score;
            newScore.time = time;
            newScore.date = QDate::currentDate();
            highScoreList.append(newScore);
            newHighScoreIndex = highScoreList.size()-1;
        }
    }

    if (highScoreList.size() > 5)
        highScoreList.removeLast();

// write to settings
    settings->beginWriteArray(GS_GROUP_HIGHSCORES, highScoreList.size());
    for (int i = 0; i < highScoreList.size(); ++i) {
        settings->setArrayIndex(i);
        settings->setValue("name", highScoreList.at(i).name);
        settings->setValue("score", highScoreList.at(i).score);
        settings->setValue("time", highScoreList.at(i).time);
        settings->setValue("date", highScoreList.at(i).date);
    }
// write ends
    settings->endArray();

    // Updates model -> emits signal after update
    highScoreModel->updateModel(highScoreList);
    return newHighScoreIndex;
}

/*!
  Reads high scores from settings file.
*/
void GameSettings::readHighScore()
{
    highScoreList.clear();

    int size = settings->beginReadArray(GS_GROUP_HIGHSCORES);

    for (int i = 0; i < size; ++i) {
        settings->setArrayIndex(i);
        HighScore score;
        score.name = settings->value("name").toString();
        score.score = settings->value("score").toInt();
        score.time = settings->value("time").toString();
        score.date = settings->value("date").toDate();
        highScoreList.append(score);
    }
    settings->endArray();
    // Updates model
    highScoreModel->updateModel(highScoreList);
}

/*!
  Gets HighScore mode generated from settings high score.
*/
HighScoreModel* GameSettings::getHighScoreModel()
{
    return highScoreModel;
}
